package cn.hanyx.coder.core.concurrent.juc.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import java.util.concurrent.Semaphore;

/**
 * UsualSemaphoreSample]
 * 线程试图获得工作允许，得到许可则进行任务，然后释放许可
 * 这时等待许可的其他线程，就可获得许可进入工作状态, 直到全部处理结束
 *
 * @author hanyx
 * @date 2020/09/24
 */
public class UsualSemaphoreSample {

    private static ExecutorService threadPool = Executors.newFixedThreadPool(30);

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 30; i++) {
            threadPool.execute(new SemaphoreWorker(semaphore));
        }
//        threadPool.shutdown();
    }
}

class SemaphoreWorker implements Runnable {

    private Semaphore semaphore;

    private String name;

    public SemaphoreWorker(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            log("save!");
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    private void log(String msg) {
        if (name == null) {
            name = Thread.currentThread().getName();
        }
        System.out.println(name + " " + msg);
    }
}